package com.tangyuan.manager;

import com.tangyuan.feignapis.user.IUserActionFeignClient;
import com.tangyuan.feignapis.user.IUserLikeFeignClient;
import com.tangyuan.model.*;
import com.tangyuan.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/*
管理员所有任务的工具类
 */
@Slf4j
@Component
public class AutoManager {

    @Autowired
    private IUserLikeFeignClient userLikeFeignClient;
    @Autowired
    private UserCoordinationService userCoordinationService;
    @Autowired
    private UserCoordination2Service userCoordination2Service;
    @Autowired
    private MovieCoordinationService movieCoordinationService;
    @Autowired
    private IUserActionFeignClient userActionFeignClient;

    /**
     * 任务 1.
     * 更新三表任务：
     * 管理员根据userAction和userLike表，跟新相关三个推荐表
     */
    @Transactional
    public void updateTask(){
        //查找最后一次更新时间
        Date time = userCoordinationService.getMaxUpdateTime();
        //根据最后一次更新时间查询用户观看数据
        List<UserAction> userActions = userActionFeignClient.getYesterdayUserActionData(time);
        if(CollectionUtils.isEmpty(userActions)){
            log.info("昨日没有user_action表数据插入");
            return;
        }
        List<Long> userIds = userActions.stream().map(UserAction::getUserId).distinct().collect(Collectors.toList());
        //根据用户查询User_like表
        List<UserLike> likes = userLikeFeignClient.selectUserLikeListByIds(userIds);
        //保存userCoordination表
        userCoordinationService.saveUserCoordination(likes);
        //保存userCoordination2表
        userCoordination2Service.saveUserCoordination2(userActions,likes);
        //保存movieCoordination表
        movieCoordinationService.saveMovieCoordination(userActions);
    }
}
